package com.example.mydemo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.example.mydemo.utils.StorageUtils;

import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StartMainActivity extends AppCompatActivity {
    public static String phoneNumber;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置key
        StorageUtils.SetKey("PHONE_NUMBER");
        // 检查目的联系人是否存在
        phoneNumber= StorageUtils.getString(StartMainActivity.this);
        if(phoneNumber!=null)
        {
            Intent intent = new Intent(StartMainActivity.this, MainActivity.class);
            intent.putExtra("PHONE_NUMBER", phoneNumber);
            StorageUtils.SetValue(phoneNumber);
            startActivity(intent);
        }else
        {
            setContentView(R.layout.startactivity);
            findViewById(R.id.buttonSubmit).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    EditText textView = findViewById(R.id.number);
                    String number = textView.getText().toString();
                    //设置Value
                    StorageUtils.SetValue(number);
                    //保存键值对
                    StorageUtils.saveString(StartMainActivity.this);
                    phoneNumber=StorageUtils.getString(StartMainActivity.this);
                    StorageUtils.SetValue(phoneNumber);
                    if (validatePhoneNumber(phoneNumber)) {
                        Intent intent = new Intent(StartMainActivity.this, MainActivity.class);
                        intent.putExtra("PHONE_NUMBER", phoneNumber);
                        startActivity(intent);
                    } else {
                        Toast.makeText(StartMainActivity.this, "请输入有效的电话号码", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }
    }

    //判断是不是全球号码
    public boolean validatePhoneNumber(String phoneNumber) {
        if (phoneNumber == null || phoneNumber.isEmpty()) {
            return false;
        }
        // 去掉前后的空格
        phoneNumber = phoneNumber.trim();

        // 定义符合E.164标准的正则表达式
        String regex = "^\\+?[1-9]\\d{1,14}$";

        // 使用正则表达式进行匹配
        boolean matches = phoneNumber.matches(regex);
        return matches;
    }
    //但判断是不是中国大陆
//    public boolean validatePhoneNumber(String phoneNumber) {
//        if (phoneNumber == null || phoneNumber.isEmpty()) {
//            return false;
//        }
//        // 去掉前后的空格
//        phoneNumber = phoneNumber.trim();
//        // 简单验证电话号码（仅适用于中国大陆）
//        String regex = "^1[3-9]\\d{9}$";
//        boolean matches = phoneNumber.matches(regex);
//        return matches;
//    }
    private boolean isContactExists(Context context, String phoneNumber) {
        ContentResolver resolver = context.getContentResolver();
        Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
        Cursor cursor = resolver.query(uri, new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME}, null, null, null);
        boolean exists = (cursor != null && cursor.moveToFirst());
        if (cursor != null) {
            cursor.close();
        }
        return exists;
    }

    private void addNewContact(Context context, String phoneNumber) {
        ArrayList<ContentProviderOperation> ops = new ArrayList<>();
        //创建一个空联系人
        ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
                .build());

        //添加电话号码信息
        ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber)
                .withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
                .build());

        try {
            context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}